package com.qys.livesMall.security.service;

import com.qys.livesMall.cache.RedisCache;
import com.qys.livesMall.cache.utils.CacheUtil;
import com.qys.livesMall.common.result.R;
import com.qys.livesMall.common.thread.holder.po.LoginUser;
import com.qys.livesMall.common.utils.uuid.IdUtils;
import com.qys.livesMall.framework.utils.SecurityUtils;
import com.qys.livesMall.security.constants.SecConstants;
import com.qys.livesMall.user.domain.entity.SysUser;
import com.qys.livesMall.user.domain.vo.login.LoginVO;
import com.qys.livesMall.user.service.ISysUserService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

import static com.qys.livesMall.common.constants.SysConstants.BEARER;

/**
 * @menu LoginService
 * @date 2023/05/22 15:38
 */
@Service
@Slf4j
public class SysLoginServer {

    @Autowired
    private ISysUserService userService;
    @Autowired
    private RedisCache redisCache;

    public static void main(String[] args) {
        String password= SecurityUtils.encryptPassword("123456");
        System.out.println(password);
        boolean b = SecurityUtils.matchesPassword("123456", password);
        System.out.println(b);
        System.err.println("end");
    }

    public R<LoginVO> login(String username, String password, HttpServletRequest request) {

        SysUser userInfo = userService.selectUserByUserName(username);
        if (userInfo == null) {
            return R.fail("账户或密码错误，请核验！");
        }
        if (!SecurityUtils.matchesPassword(password, userInfo.getPassword())) {
            return R.fail("密码错误，请核验！");
        }
        //生成登录token,保存
        LoginUser user = new LoginUser();
        BeanUtils.copyProperties(userInfo,user);
        user.setNickName(userInfo.getNickName());
        //生成令牌
        String token= IdUtils.fastUUID();
        String tokenCache=BEARER+token;
        //缓存用户信息
        String tokenKey = CacheUtil.getKey(SecConstants.RedisKeyPrefix.TOKEN, tokenCache);
        redisCache.setCacheObject(tokenKey, user, 7L, TimeUnit.DAYS);
        //缓存权限
        LoginVO vo = new LoginVO();
        vo.setToken(token);
        return R.ok(vo);
    }


    public R loginOut(String token) {
        String tokenKey = CacheUtil.getKey(SecConstants.RedisKeyPrefix.TOKEN, token);
        redisCache.deleteObject(tokenKey);
        return R.ok();
    }


}

